<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Controller;
use App\Jobs\SaveUserAvatar;
use App\Jobs\SendUserQrcode;
use App\Order;
use App\Product;
use App\Qrcode;
use App\User;
use App\UserChange;
use App\UserCoin;
use App\WechatMenu;
use Carbon\Carbon;
use EasyWeChat\Payment\Order as WMOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WechatController extends Controller
{
    protected $wechat;

    public function __construct()
    {
        $this->wechat = app('wechat');
    }

    /**
     * @function 处理微信消息
     */
    public function index()
    {
        $server = $this->wechat->server;
        $server->setMessageHandler(function ($message) {
            $openid = $message->FromUserName;
            switch ($message->MsgType) {
                case 'event':
                    switch ($message->Event) {
                        case 'subscribe':
                            $wechat_user = $this->wechat->user->get($openid);
                            $unionid = $wechat_user['unionid'];

                            if ($user = User::where('openid', $openid)->first()) {
                            } elseif ($user = User::where('unionid', $unionid)->first()) {
                                $user->openid = $openid;
                                $user->save();
                            } else {
                                $user = new User;
                                $user->openid = $openid;
                                $user->avatar = $wechat_user['headimgurl'];
                                $user->nickname = $wechat_user['nickname'];
                                $user->sex = $wechat_user['sex'];
                                $user->country = $wechat_user['country'];
                                $user->province = $wechat_user['province'];
                                $user->city = $wechat_user['city'];
                                $user->password = '';
                                $user->save();

                                dispatch(new SaveUserAvatar($user));
                            }

                            if (!$user->unionid) {
                                $user->unionid = $wechat_user['unionid'];
                                $user->save();
                            }

                            //关联处理
                            if ($message->EventKey && substr($message->EventKey, 0, 8) == 'qrscene_' && !$user->finder_id) {
                                $scene_id = intval(substr($message->EventKey, 8));
                                if ($user->id != $scene_id) {
                                    $user->finder_id = $scene_id;
                                    $user->save();

                                    $finder = User::where('id', $scene_id)->first();
                                    $this->wechat->staff->message('恭喜！' . $user->nickname . '成为你的粉丝。')->to($finder->openid)->send();
                                }
                            }

                            $this->wechat->staff->message('您好，欢迎关注欢乐菠萝！')->to($openid)->send();
                            break;
                        case 'unsubscribe':
                            break;
                        case 'CLICK':
                            switch ($message->EventKey) {
                                case 'QRCODE':
                                    $user = User::where('openid', $openid)->first();

                                    $qrcode = Qrcode::find(4);
                                    dispatch(new SendUserQrcode($user, $qrcode));

                                    $this->wechat->staff->message('二维码正在生成中，稍后通过消息发给您')->to($openid)->send();
                                    break;
                                case 'CHAT':
                                    $this->wechat->staff->message('快乐大菠萝微信群，每天红包活动，福利多多，惊喜多多，加欢乐客服微信号：yskj8868，邀约进群，抢大红包。')->to($openid)->send();
                                    break;
                                case 'SIGN':
                                    return <<<EOF
每日一签，已迁移到〈聚宝盆游戏〉的每日一赚，请下载app赚取更多金币！
好玩是第一生产力！
EOF;
                                    break;
                            }
                            break;
                    }
                    break;
                case 'text':
                    return "您的消息我们已经收到了哦！";
                    break;
                default:
                    return "您好，欢迎关注欢乐菠萝！";
            }
        });
        $response = $server->serve();
        $response->send();
    }

    /**
     * 商品支付
     * @param $user
     * @param $mallOrder
     * @param $goods
     * @param string $type
     * @return mixed
     */
    public function productsPay($user, $mallOrder, $products, $type = 'JSAPI')
    {
        $wechat = $this->wechat;
        $openid = $user->openid;

        $order = new Order;
        $order->trade_id = '';
        $order->user_id = $user->id;
        $order->related_id = $mallOrder->id;
        $order->total = ($products->need_jb / 100);
        $order->type = 2;//1.product 2.mall
        $order->save();

        $order->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . $order->id;
        $order->save();

        $attributes = [
            'trade_type' => $type,
            'body' => $products->name,
            'detail' => $products->name,
            'out_trade_no' => $order->trade_id,
            'total_fee' => ($order->total * 100),
            'openid' => $openid,
        ];
        $order = new WMOrder($attributes);
        $data = $wechat->payment->prepare($order);

        if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
            $prepay_id = $data->prepay_id;
            $data = $wechat->payment->configForPayment($prepay_id);

            return json_encode(['code' => 1000, 'results' => $data]);
        }
        return json_encode(['code' => 9000, 'msg' => '创建订单失败！']);
    }

    /**
     * @function 商品提货差价
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function prepare(Request $request)
    {
        $user = auth()->user();
        $type = 'JSAPI';

        $wechat = $this->wechat;
        $openid = $user->openid;

        if ($request->has('charge')) {
            $charge = intval(abs($request->input('charge')));
            if ($charge) {
                if (!$product = Product::where('value', $charge)->where('type', 1)->first()) {
                    $product = new Product;
                    $product->business_id = 0;
                    $product->name = '商品提货差价';
                    $product->price = $charge;
                    $product->type = 1;
                    $product->value = $charge;
                    $product->save();
                }
            }
        }

        $order = new Order;
        $order->trade_id = '';
        $order->user_id = $user->id;
        $order->related_id = $product->id;
        $order->total = $product->price;
        $order->type = 1;//1.product 2.mall
        $order->save();

        $order->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . $order->id;
        $order->save();

        $attributes = [
            'openid' => $openid,
            'trade_type' => $type,
            'body' => $product->name,
            'detail' => $product->name,
            'out_trade_no' => $order->trade_id,
            'total_fee' => ($order->total * 100),
        ];

        $order = new WMOrder($attributes);
        $data = $wechat->payment->prepare($order);

        if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
            $prepay_id = $data->prepay_id;
            $data = $wechat->payment->configForPayment($prepay_id);

            return response()->json(['code' => 1000, 'results' => $data]);
        }

        return response()->json(['code' => 9000, 'msg' => '创建订单失败！', 'data' => $data]);
    }

    /**
     * @function 微信支付回调方法
     *
     * @return mixed
     */
    public function notify()
    {
        $wechat = $this->wechat;
        $response = $wechat->payment->handleNotify(function ($notify, $successful) {

            try {
                DB::beginTransaction();
                $order = Order::where('trade_id', $notify->out_trade_no)->where('status', 0)->sharedLock()->first();
                if (!$order) {
                    return true;
                }

                if ($successful) {
                    $order->status = 1;
                    $order->save();

                    app('App\Http\Controllers\Api\OrderController')->notify($order);

                }
                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                return false;
            }

            return true;
        });

        return $response;
    }

    /**
     * @function 兑换红包
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lucky_money(Request $request)
    {
        $user = auth()->user();

        $wechat = $this->wechat;
        $openid = $user->openid;

        if ($user->ZS < 10) {
            return response()->json(['code' => 9002, 'msg' => '红包不足10，无法发放！']);
        }

        $amount = $request->input('amount', 0);
        if (!in_array($amount, array(10, 50, 100, 200))) {
            return response()->json(['code' => 9004, 'msg' => '红包金额有误，请重新选择']);
        }

        $key = Carbon::now()->format('YmdHi');

        $change = $user->changes()->orderBy('created_at', 'desc')->first();
        if ($change && $change->created_at->format('YmdHi') == $key) {
            return response()->json(['code' => 9003, 'msg' => '一分钟只能发放红包一次，请稍候再试！']);
        }

        if ($user->changes()->where('created_at', '>=', Carbon::today()->startOfDay())->count() >= 10) {
            return response()->json(['code' => 9004, 'msg' => '由于微信限制，每天只能发放红包10次，请明天再试吧！']);
        }

        try {
            if ($user->ZS < $amount) {
                return response()->json(['code' => 9004, 'msg' => '红包不足，无法发放！']);
            }

            $userChange = new UserChange;
            $userChange->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
            $userChange->user_id = $user->id;
            $userChange->key = $user->id . '-' . Carbon::now()->format('YmdHi');
            $userChange->amount = $amount;
            $userChange->save();

            $key = '0-' . $user->id . '-' . -$amount . '-' . time() . '-4';
            UserCoin::log(0, $user->id, UserCoin::TYPE_ZS, -$amount, '提现', $key);

            $luckyMoney = $wechat->lucky_money;
            $luckyMoneyData = [
                'mch_billno' => $userChange->trade_id,
                'send_name' => '欢乐菠萝',
                're_openid' => $openid,
                'total_num' => 1,
                'total_amount' => $amount * 100,
                'wishing' => '兑换红包',
                'act_name' => '欢乐菠萝',
                'remark' => '欢乐菠萝',
            ];
            $data = $luckyMoney->sendNormal($luckyMoneyData);

            if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
                $userChange->status = 1;
                $userChange->save();

                return response()->json(['code' => 1000, 'results' => ['ZS' => $user->ZS]]);
            } else {

                //发出警报
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send_batch.json");
                curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_HEADER, FALSE);
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => '13726873311', 'message' => '你好，发现异常情况。项目：欢乐菠萝，UID：' . $user->id . '，描述：' . $data->err_code_des . '。【小妖传媒】'));
                $res = curl_exec($ch);
            }
        } catch (\Exception $e) {
        }

        return response()->json(['code' => 9000, 'msg' => '兑换红包失败，钻石将在5分钟内退回您的账户！']);
    }

    /**
     * @function 微信菜单栏
     *
     * @return mixed
     */
    public function menu()
    {
        $menu = $this->wechat->menu;

        $menu->destroy();

        $parameters = array(
            'view' => 'url',
            'click' => 'key'
        );
        $buttons = array();

        $wechatMenuGroup = WechatMenu::where('parent_id', 0)->orderBy('sort', 'asc')->get();
        foreach ($wechatMenuGroup as $group) {
            if ($group->children()->count()) {
                $subs = array();
                foreach ($group->children()->orderBy('sort', 'asc')->get() as $wechatMenu) {
                    $subs[] = array(
                        'type' => $wechatMenu->type,
                        'name' => $wechatMenu->name,
                        $parameters[$wechatMenu->type] => $wechatMenu->parameter
                    );
                }

                $buttons[] = array(
                    'name' => $group->name,
                    'sub_button' => $subs
                );
            } else {
                $buttons[] = array(
                    'type' => $group->type,
                    'name' => $group->name,
                    $parameters[$group->type] => $group->parameter
                );
            }
        }

        $response = $menu->add($buttons);

        return $response;
    }

    /**
     * 微信分享
     *
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function share(Request $request)
    {
        $no = str_random(16);

        $da['appId'] = env('WECHAT_APPID');

        $da['timestamp'] = time();
        $da['nonceStr'] = $no;

        $da['error'] = '';
        $da['type'] = TRUE;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            $da['error'] = 'Errno' . curl_error($ch);
            $da['type'] = FALSE;
        }
        curl_close($ch);
        $postObj = json_decode($tmpInfo);

        //获取jsapi_ticket
        $ls = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $postObj->access_token . '&type=jsapi');
        $js = json_decode($ls, true);
        $da['jsapi_ticket'] = $js['ticket'];
        $str1 = 'jsapi_ticket=' . $da['jsapi_ticket'] . '&noncestr=' . $no . '&timestamp=' . $da['timestamp'] . '&url=' . $request->input('site_url');

        $da['signature'] = sha1($str1);

        return response()->json($da);
    }
}
